package com.yc.blog.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;

import com.yc.blog.bean.AdminInfo;
import com.yc.blog.biz.IAdminInfoBiz;
import com.yc.blog.biz.impl.AdminInfoBizImpl;
import com.yc.blog.util.FileUploadUtil;
import com.yc.blog.util.SessionKeys;

@WebServlet("/admin")
public class AdminInfoController extends BasicController{
	private static final long serialVersionUID = -3517058055121493619L;
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String op = request.getParameter("op");
		
		if("login".equals(op)) {	//登陆操作
			login(request,response);
		}else if("add".equals(op)) {//添加操作
			add(request,response);
		}else if("findAll".equals(op)) { //查询所有
			findAll(request,response);
		}else if("info".equals(op)) { //获取登录用户信息的方法
			info(request,response);
		}
	}

	private void info(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession();
		Object obj = session.getAttribute(SessionKeys.CURRENTBACKLOGINACCOUNT);
		if(obj == null) {	//说明没有登陆
			this.send(response, 500, null);
			return;
		}
		this.send(response, 200, obj);
	}

	private void findAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
		IAdminInfoBiz adminInfoBiz=new AdminInfoBizImpl();
		List<AdminInfo> list=adminInfoBiz.findAll();
		if(list !=null && !list.isEmpty()) {
			this.send(response, 200,list);
			return;
		}
		this.send(response, 500,null);
		
	}

	private void add(HttpServletRequest request, HttpServletResponse response) {
		FileUploadUtil fuu=new FileUploadUtil();
		PageContext pageContext=JspFactory.getDefaultFactory().getPageContext(this, request, response, null, true, 8192, true);
		try {
			Map<String,String> map=fuu.upload(pageContext);
			IAdminInfoBiz adminInfoBiz=new AdminInfoBizImpl();
			int result=adminInfoBiz.add(map.get("aname"),map.get("pwd"), map.get("photo"));
			this.send(response, result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String aname = request.getParameter("aname");
		String pwd = request.getParameter("pwd");
		
		IAdminInfoBiz adminInfoBiz = new AdminInfoBizImpl();
		AdminInfo adminInfo = adminInfoBiz.login(aname, pwd);
		
		if(adminInfo == null) {
			this.send(response, 500, null);
			return;
		}
		
		//如果登陆成功，需要将此登录用户信息存到session
		request.getSession().setAttribute(SessionKeys.CURRENTBACKLOGINACCOUNT, adminInfo);
		this.send(response, 200, null);
	}
	
	
	
	
}
